package com.simon.app.utils;

import android.content.ContextWrapper;

import com.simon.app.R;
import com.simon.app.entity.RuleDetail;
import com.simon.app.entity.RuleEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ParseUtil {

    // 读取自定义广告类型JSON文件生成规则实体列表
    public static List<RuleEntity> loadAdRules(ContextWrapper ctx) {
        List<RuleEntity> ruleEntityList = new ArrayList<>();

        try {
            InputStream inputStream = ctx.getResources().openRawResource(R.raw.ad_rules);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            bufferedReader.close();
            inputStream.close();

            JSONArray jsonArray = new JSONArray(sb.toString());
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Iterator<String> keys = jsonObject.keys();
                while (keys.hasNext()) {
                    String key = keys.next();
                    String value = jsonObject.getString(key);

                    JSONObject ruleEntityJson = new JSONObject(value);
                    JSONArray popupRules = ruleEntityJson.getJSONArray("popup_rules");

                    RuleEntity ruleEntity = new RuleEntity();
                    ArrayList<RuleDetail> ruleDetails = new ArrayList<>();
                    for (int j = 0; j < popupRules.length(); j++) {
                        JSONObject ruleObject = popupRules.getJSONObject(j);
                        RuleDetail ruleDetail = new RuleDetail(ruleObject.getString("id"), ruleObject.getString("action"));
                        ruleDetails.add(ruleDetail);
                    }

                    ruleEntity.setRules(ruleDetails);
                    ruleEntityList.add(ruleEntity);
                }
            }

            return ruleEntityList;
        } catch (IOException | JSONException e) {
            LogUtil.i("异常报错:" + e.getMessage());
            e.printStackTrace();
        }

        return ruleEntityList;
    }
}
